package org.parademo.equations.test;

import java.sql.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Ajit Skanda Kumaraswamy
 */
public class DBConnectivity {

    String userName = "root";
    String password = "root123";
    String dbName = "test";
    String serverName = "localhost";
    Connection connection = null;
    Statement stmt = null;
    ResultSet rs = null;

    public void accessDB() {

        try {

            String driver = "com.mysql.jdbc.Driver";
            Class.forName(driver);
            String url = "jdbc:mysql://" + serverName + "/" + dbName;
            connection = DriverManager.getConnection(url, userName, password);

            stmt = connection.createStatement();	
            rs = stmt.executeQuery("Select * from `test_table`");

           while(rs.next()) {

               System.out.println("content_id : " + rs.getBigDecimal("content_id") + "\n");
               System.out.println("aggregated_weight : " + rs.getDouble("aggregated_weight") + "\n");
               System.out.println("time_of_change : " + rs.getTimestamp("time_of_change") + "\n");
               System.out.println("vote : " + rs.getInt(4) + "\n\n");
           }

        } catch (SQLException ex) {

            Logger.getLogger(DBConnectivity.class.getName()).log(Level.SEVERE, null, ex);

        } catch (Exception e) {

            System.out.println("Error !!");
            e.printStackTrace();
        } finally {


            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException sqlEx) {} // ignore

                rs = null;
            }

            if (stmt != null) {
                try {
                    stmt.close();
                } catch (SQLException sqlEx) {} // ignore

                stmt = null;
            }

            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException sqlEx) {} // ignore

                connection = null;
            }
        }
    }

    public static void main(String[] argv) {
        
        DBConnectivity test = new DBConnectivity();
        test.accessDB();

    }
}
